<?php

namespace app\admin\controller;

use support\Request;
use support\Response;
use app\model\AdminModel;
use app\model\AdminLogModel;
use Exception;

class AdminController
{
    /**
     * 管理员登录
     * @param Request $request
     * @return Response
     */
    public function login(Request $request): Response
    {
        try {
            $data = $request->post();
            
            if (empty($data['username']) || empty($data['password'])) {
                throw new Exception('用户名和密码不能为空');
            }

            $admin = AdminModel::where('username', $data['username'])->first();
            if (!$admin) {
                throw new Exception('用户不存在');
            }

            if ($admin->password !== md5($data['password'])) {
                throw new Exception('密码错误');
            }

            if ($admin->status !== 1) {
                throw new Exception('账号已被禁用');
            }

            // 生成新的访问令牌
            $token = md5(uniqid((string)time(), true));
            if (!$admin->updateAccessToken($token)) {
                throw new Exception('登录失败');
            }

            // 记录登录日志
            AdminLogModel::record(
                $admin->id,
                'admin.login',
                $admin->username,
                $request->getRealIp()
            );

            return json([
                'data' => [
                    'token' => $token,
                    'id' => $admin->id
                ],
                'msg' => '登录成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取管理员信息
     * @param Request $request
     * @return Response
     */
    public function info(Request $request): Response
    {
        try {
            $admin = $request->admin;
            if (!$admin) {
                throw new Exception('请先登录');
            }

            return json([
                'data' => [
                    'id' => $admin->id,
                    'username' => $admin->username,
                    'status' => $admin->status
                ],
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 管理员退出登录
     * @param Request $request
     * @return Response
     */
    public function logout(Request $request): Response
    {
        try {
            $admin = $request->admin;
            if (!$admin) {
                throw new Exception('请先登录');
            }

            // 清除访问令牌
            if (!$admin->updateAccessToken('')) {
                throw new Exception('退出失败');
            }

            // 记录退出日志
            AdminLogModel::record(
                $admin->id,
                'admin.logout',
                '管理员退出登录'
            );

            return json([
                'data' => null,
                'msg' => '退出成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取管理员列表
     * @param Request $request
     * @return Response
     */
    public function index(Request $request): Response
    {
        try {
            $current = (int)$request->get('current', 1);
            $pageSize = (int)$request->get('pageSize', 10);
            
            // 构建查询
            $query = AdminModel::query();
            
            // 搜索条件
            $username = $request->get('username');
            if ($username) {
                $query->where('username', 'like', "%{$username}%");
            }
            
            $status = $request->get('status');
            if ($status !== null && $status !== '') {
                $query->where('status', (int)$status);
            }
            
            // 获取总数
            $total = $query->count();
            
            // 获取分页数据
            $list = $query->orderBy('id', 'desc')
                ->offset(($current - 1) * $pageSize)
                ->limit($pageSize)
                ->get(['id', 'username', 'status', 'created_at', 'updated_at']);

            foreach ($list as &$item) {
                $item->created_at = date('Y-m-d H:i:s', $item->created_at);
                $item->updated_at = date('Y-m-d H:i:s', $item->updated_at);
            }
            
            return json([
                'data' => [
                    'list' => $list,
                    'total' => $total
                ],
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    public function submit(Request $request) {
        try {
            $data = $request->post();

            if(empty($data['username'])){
                throw new Exception('用户名不能为空');
            }

            if (empty($data['id'])) {
                $admin_count = AdminModel::where('username', $data['username'])->count();
                if ($admin_count > 0) {
                    throw new Exception('用户名已存在');
                }

                $admin = new AdminModel();
                $admin->password = md5($data['password']);
            } else {
                $admin = AdminModel::find($data['id']);
                if (!$admin) {
                    throw new Exception('管理员不存在');
                }

                if(!empty($data['password'])){
                    $admin->password = md5($data['password']);
                }
            }

            $admin->username = $data['username'];
            
            $admin->status = $data['status'];
            $admin->save();

            return json([
                'data' => null,
                'msg' => '操作成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }
}
